import { defineStore } from 'pinia'
import { getUserInfo as getUserInfoApi } from '@/api/modules/user'
import { login as apiLogin } from '@/api/modules/login'
import type { Login } from '@/types/api'
import { setToken, clearToken } from '@/utils/token'
import { removeRouteListener } from '@/utils/route-listener'
import type { UserInfo, UserState } from '../../types/users'
import { useTabsStore } from '@/stores'
const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userId: '',
    userInfo: {
      userName: undefined,
      avatar: undefined,
      role: ''
    }
  }),

  getters: {
    computedUserInfo(state: UserState): UserInfo {
      //因为用户信息会用$reset进行重设，所以外面使用的时候使用这个计算属性，这样当我reset用户信息时外面也能监听到。
      return { ...state.userInfo }
    }
  },

  actions: {
    // switchRoles() {
    //   return new Promise((resolve) => {
    //     this.role = this.role === "user" ? "admin" : "user";
    //     resolve(this.role);
    //   });
    // },

    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial)
    },

    // Reset user's information
    reset() {
      this.$reset()
    },

    // Get user's information
    async info() {
      const res = await getUserInfoApi()
      this.setInfo(res.result)
    },

    // Login
    async login(loginForm: Login.ReqLoginForm) {
      try {
        const res = await apiLogin(loginForm)
        setToken(res.result.token)
      } catch (err) {
        clearToken()
        throw err
      }
    },

    // Logout
    logout() {
      this.reset()
      clearToken()
      removeRouteListener()
      const tabsStore = useTabsStore()
      tabsStore.closeMultipleTab() // 清除上个账号的 tab 信息
    }
  }
})

export default useUserStore
